<template>
  <div class="sjplatformAdd">
    <el-form label-width="100px">
      <el-form-item label="项目名称：">
        <span>{{ projectStore.projectModel.projectName }}</span>
      </el-form-item>
      <el-form-item label="计划简介：">
        <el-input v-model="projectStore.scheduleModel.mark" type="textarea" />
      </el-form-item>
      <el-form-item label="计划时间：">
        <el-date-picker v-model="projectStore.scheduleModel.startTime" clearable type="date"
          placeholder="开始日期" />~<el-date-picker v-model="projectStore.scheduleModel.endTime" clearable type="date"
          placeholder="结束日期" />
      </el-form-item>
    </el-form>

    <!-- 任务表单开始 -->
    <div v-for="(schedule, tIndex) in projectStore.scheduleModel.tasks" :key="tIndex" class="sjplatform-form-item">
      <el-form-item :key="schedule.id" :label="'任务' + (tIndex + 1) + '：'">
        <el-input class="item-input" v-model="schedule.taskName" placeholder="请输入任务名称" />
        <el-tooltip :content="'删除任务' + (tIndex + 1)" placement="bottom" effect="light">
          <i class="del-icon" @click="delSchedule(tIndex)"></i>
        </el-tooltip>
      </el-form-item>
      <el-form-item label="描述：">
        <el-input v-model="schedule.mark" type="textarea" placeholder="请输入任务描述" />
      </el-form-item>
      <el-form-item label="父级：" v-if="schedule.sort > 1">
        <el-select v-model="schedule.pId" clearable placeholder="请选择父级任务"
          @update:modelValue="setSchedulePName(schedule, schedule.pId)">
          <el-option
            v-for="r in projectStore.scheduleModel.tasks.filter(r => r.id !== schedule.id && r.sort < schedule.sort && r.taskName != '')"
            :key="r.id" :label="r.taskName" :value="r.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="计划时间：">
        <el-date-picker v-model="schedule.startTime" clearable type="date" placeholder="开始日期" />~<el-date-picker
          v-model="schedule.endTime" clearable type="date" placeholder="结束日期" />
      </el-form-item>
      <el-form-item label="关联需求：">
        <el-input v-model="schedule.rName" @click="showRequirementTree(tIndex, 'r')" placeholder="点击选择需求" />
      </el-form-item>
      <el-form-item label="关联功能：">
        <el-input v-model="schedule.fTitle" @click="showRequirementTree(tIndex, 'f')" placeholder="点击选择功能" />
      </el-form-item>
      <el-form-item label="负责人：">
        <el-input v-model="schedule.personNames" placeholder="点击选择负责人"
          @click="openUserSelectForm('选择任务负责人', false, tIndex)" clearable @clear="clearpersons" />
      </el-form-item>
    </div>
    <!-- 任务表单结束 -->

    <el-form label-width="100px">
      <el-form-item label="任务操作：">
        <el-tooltip content="添加任务" placement="bottom" effect="light">
          <i class="add-icon" @click="addScheduleItem"></i>
        </el-tooltip>
        <el-tooltip content="导入任务" placement="bottom" effect="light">
          <i class="import-icon"></i>
        </el-tooltip>
        <el-tooltip content="生成进度计划文档" placement="bottom" effect="light">
          <i class="build-icon"></i>
        </el-tooltip>
      </el-form-item>
      <el-form-item label="附件：">
        <FileUpload ref="fileUpload" :historyFileList="historyFileList" @file-delete="handleFileDeleted" />
      </el-form-item>
    </el-form>
  </div>
  <el-dialog v-model="newRTVisible" title="选择关联需求" width="30%" draggable :destroy-on-close="true"
    :close-on-click-modal="false" class="fullscreen-dialog">
    <RequirementTree ref="rTreeRef" :projectId="projectStore.scheduleModel.projectId" />
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="confirm">确定</el-button>
      </span>
    </template>
  </el-dialog>
  <el-dialog v-model="isOpenUserSelectForm" :title="formTitle" width="50%" draggable :destroy-on-close="true">
    <UserSelect :initSelectedUser="initSelectedUser" />
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="isOpenUserSelectForm = false; indexTmp = 0;">取消</el-button>
        <el-button type="primary" @click="confirmPerson">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue';
import FileUpload from "../../Common/FileUpload.vue";
import { useProjectTable } from "../../../hooks/ProjectManager/Start/useProjectTable";
import { useProjectSchedule } from "../../../hooks/ProjectManager/Plan/useProjectSchedule";
import RequirementTree from '../Common/RequirementTree.vue';
import UserSelect from "../../../components/SystemManager/User/UserSelect.vue";
import commonUtil from '../../../utils/common';
import emitter from "../../../utils/emitter";

let historyFileList = ref();
let newRTVisible = ref(false);
let rTreeRef = ref(null);
let indexTmp = 0;//临时存储任务索引
let { projectTable, projectStore, getProjectDoc, deleteProjectDoc } = useProjectTable(1, 10);
let { getScheduleDetailByProjectId } = useProjectSchedule(1, 10);

if (projectStore.scheduleModel.projectId) {
  getScheduleDetailByProjectId(projectStore.scheduleModel.projectId).then(() => {
    //如果任务主表ID为空则表示还没有配置，生成一个主ID并给projectId赋值
    if (!projectStore.scheduleModel.id) {
      projectStore.scheduleModel.id = commonUtil.Methods.generateGUID();
      projectStore.scheduleModel.projectId = projectStore.projectModel.id;
    }
  })
}

//附件
getProjectDoc(projectStore.projectModel.id, 2).then(() => {
  historyFileList.value = projectTable.documentList;
});

/*--------------------选择负责人开始--------------------*/
let isOpenUserSelectForm = ref(false); //是否打开用户选择窗口
let formTitle = ref("");
let initSelectedUser = reactive({
  single: false,
  selectedrow: [],
});
//打开人员选择窗口
function openUserSelectForm(title, value, index) {
  formTitle.value = title;
  indexTmp = index;
  initSelectedUser.single = value;
  initSelectedUser.selectedrow = projectStore.scheduleModel.tasks[indexTmp].personIds.split(',');
  isOpenUserSelectForm.value = true;
}
//清理负责人
function clearpersons() {
  projectStore.scheduleModel.tasks[indexTmp].presonNames = '';
  projectStore.scheduleModel.tasks[indexTmp].personIds = '';
  projectStore.scheduleModel.tasks[indexTmp].persons = [];
  projectStore.scheduleModel.tasks[indexTmp].personsSelected = [];
}
//确认选择的负责人
function confirmPerson() {
  emitter.emit("confirmSelectedUser");
}
//供用户选择调用设置选择的项
emitter.on("set-selected-user", (SelectionRows: any) => {
  let selectedUserId = [];
  let selectedUserName = [];
  clearpersons();
  for (let item of SelectionRows) {
    selectedUserId.push(item.id);
    selectedUserName.push(item.realName);
    projectStore.scheduleModel.tasks[indexTmp].persons.push({ userId: item.id, userName: item.realName });
  }
  projectStore.scheduleModel.tasks[indexTmp].personsSelected = selectedUserId;

  projectStore.scheduleModel.tasks[indexTmp].personNames = selectedUserName.join(",");
  projectStore.scheduleModel.tasks[indexTmp].personIds = selectedUserId.join(",");

  isOpenUserSelectForm.value = false;
  indexTmp = 0;
});
/*--------------------选择负责人结束--------------------*/

/*--------------------任务处理开始--------------------*/
//添加任务
function addScheduleItem() {
  // 添加新的任务对象
  projectStore.scheduleModel.tasks.push({
    id: commonUtil.Methods.generateGUID(),
    projectId: projectStore.projectModel.id,
    mId: projectStore.scheduleModel.id,
    taskName: '',
    mark: '',
    pId: '',
    pName: '',//父级任务
    rId: '',
    rName: '',
    fId: '',
    fTitle: '',
    sort: projectStore.scheduleModel.tasks.length + 1,//排序
    startTime: null,//开始时间
    endTime: null,//结束时间
    personIds: '',
    personNames: '',
    persons: [],//负责人
    personsSelected: [],//选中的负责人
  });
}
//删除任务
function delSchedule(reqIndex) {
  // 向指定任务的子项列表中添加新子项
  projectStore.scheduleModel.tasks.splice(reqIndex, 1);
}

//设置任务父级名称
function setSchedulePName(item, value) {
  // 找到对应的父级任务
  const parent = projectStore.scheduleModel.tasks.find(r => r.id === value);
  // 如果找到了父级任务，设置 pId 和 pName
  if (parent) {
    item.pId = parent.id;
    item.pName = parent.taskName;
  }
}
/*--------------------任务处理结束--------------------*/

/*--------------------关联需求开始--------------------*/
let selectType = ref('r');//是选择需求还是功能，r=需求，f=功能
//显示需求树
function showRequirementTree(index, type) {
  newRTVisible.value = true;
  selectType.value = type;
  indexTmp = index;
}
//取消关联需求
function cancel() {
  indexTmp = 0;
  newRTVisible.value = false;
}

//确定关联需求
function confirm() {
  if (selectType.value == 'r') {
    projectStore.scheduleModel.tasks[indexTmp].rId = rTreeRef.value.exposeNode.id;
    projectStore.scheduleModel.tasks[indexTmp].rName = rTreeRef.value.exposeNode.value;
  }
  if (selectType.value == 'f') {
    //需求
    projectStore.scheduleModel.tasks[indexTmp].rId = rTreeRef.value.exposeNode.rId;
    projectStore.scheduleModel.tasks[indexTmp].rName = rTreeRef.value.exposeNode.rName;
    //功能
    projectStore.scheduleModel.tasks[indexTmp].fId = rTreeRef.value.exposeNode.id;
    projectStore.scheduleModel.tasks[indexTmp].fTitle = rTreeRef.value.exposeNode.value;
  }
  indexTmp = 0;
  newRTVisible.value = false;
}
/*--------------------关联需求结束--------------------*/

// 处理文件删除事件
async function handleFileDeleted(objectId) {
  if (await deleteProjectDoc(objectId)) {
    historyFileList.value = historyFileList.value.filter(file => file.objectId !== objectId);
  }
}
</script>